export default class Fullscreen {
  constructor(elem) {
    const eventName = [
      "fullscreenchange",
      "mozfullscreenchange",
      "webkitfullscreenchange",
      "msfullscreenchange",
    ];
    const onFullscreenChange = (e) => {
      if (typeof this.onFullscreenChange === "function") {
        e.isFullScreen = this.isFullScreen();
        this.onFullscreenChange(e);
      }
    };
    this.elem = elem || document.documentElement;
    if (!this.elem.listenFullscreenChange) {
      eventName.forEach((name) => {
        this.elem.addEventListener(name, onFullscreenChange, false);
      });
      this.elem.listenFullscreenChange = true;
    }
  }
  getElement() {
    return (
      document.fullscreenElement ||
      document.mozFullScreenElement ||
      document.msFullScreenElement ||
      document.webkitFullscreenElement ||
      null
    );
  }
  isFullScreen() {
    return !!(
      document.fullscreen ||
      document.mozFullScreen ||
      document.webkitIsFullScreen ||
      document.webkitFullScreen ||
      document.msFullScreen
    );
  }
  enable() {
    return (
      document.fullscreenEnabled ||
      document.mozFullScreenEnabled ||
      document.webkitFullscreenEnabled ||
      document.msFullscreenEnabled
    );
  }
  enter(element) {
    if (!element) {
      element = document.documentElement;
    }
    // 判断各种浏览器，找到正确的方法
    const requestMethod =
      element.requestFullScreen || // W3C
      element.webkitRequestFullScreen || // Chrome等
      element.mozRequestFullScreen || // FireFox
      element.msRequestFullScreen; // IE11
    if (requestMethod) {
      requestMethod.call(element);
    } else if (typeof window.ActiveXObject !== "undefined") {
      // for Internet Explorer
      const WScript = new window.ActiveXObject("WScript.Shell");
      if (WScript !== null) {
        WScript.SendKeys("{F11}");
      }
    }
  }
  exit() {
    // 判断各种浏览器，找到正确的方法
    const exitMethod =
      document.exitFullscreen || // W3C
      document.mozCancelFullScreen || // Chrome等
      document.webkitExitFullscreen || // FireFox
      document.webkitExitFullscreen; // IE11
    if (exitMethod) {
      exitMethod.call(document);
    } else if (typeof window.ActiveXObject !== "undefined") {
      // for Internet Explorer
      const WScript = new window.ActiveXObject("WScript.Shell");
      if (WScript !== null) {
        WScript.SendKeys("{F11}");
      }
    }
  }
}
